package mvc.struts.annotation.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class ReflectionUtil {

	private static Logger LOGGER = LoggerFactory.getLogger(ReflectionUtil.class);
	
	/**
	 * 
	 * @param cls
	 * @return
	 */
	public static Object newInstance(Class<?> cls) {
		
		Object	instance;
		
		try
		{
			instance = cls.newInstance();
		}
		catch(Exception ex)
		{
			LOGGER.error("new instance failure", ex);
			throw	new	RuntimeException(ex);
		}
		
		return	instance;
	}
	
	/**
	 * 
	 * @param obj
	 * @param method
	 * @param args
	 * @return
	 */
	public static Object invokeMethod(Object obj, Method method, Object ...args)
	{
		Object	result = null;
		
		System.out.println("Method name: " + method.getName());
		
		try
		{
			method.setAccessible(true);
			result = method.invoke(obj, args);
		}
		catch(Exception ex)
		{
			LOGGER.error("invoke method failure", ex);
			ex.printStackTrace();
			
			throw	new RuntimeException(ex);
		}
		
		return	result;
	}
	
	/**
	 * 
	 * @param obj
	 * @param field
	 * @param value
	 */
	public static void setField(Object obj, Field field, Object value)
	{
		try
		{
			field.setAccessible(true);
			field.set(obj, value);
		}
		catch(Exception ex)
		{
			LOGGER.error("set field failure", ex);
			throw	new	RuntimeException(ex);
		}
	}
}
